package com.jzg.jcptadmin.presenter;

import android.text.TextUtils;

import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.app.AppContext;
import com.jzg.jcptadmin.base.BasePresenter;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarTypeModel;
import com.jzg.jcptadmin.viewinterface.CarTypeSelectInterface;

import java.util.HashMap;
import java.util.Map;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.jzg.jcptadmin.app.AppContext.isNetWork;

/**
 *
 * @author zealjiang
 * @time 2017/3/17 15:10
 */
public class CarTypeSelectPresenter extends BasePresenter<CarTypeSelectInterface>{

    private DataManager dataManager;
    private Subscription mSubscription;
    private CarTypeSelectInterface mView;

    public CarTypeSelectPresenter(DataManager dataManager){
        super();
        this.dataManager = dataManager;
    }
    @Override
    public void attachView(CarTypeSelectInterface mvpView) {
        super.attachView(mvpView);
        mView = mvpView;
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mSubscription != null) mSubscription.unsubscribe();
    }

    public void getCarTypes(String vin,String nameplate){

        if(!isNetWork){
            mView.brandSeriesFail("对不起，您的网络状况不佳，请确保已经连接网络！");
            return;
        }

        Map<String,String> params = new HashMap<>();
        params.put("vin",vin);
        params.put("nameplate",nameplate);
        params.put("userID", AppContext.getContext().getUser().getUserId() + "");
        params.put("tokenID", "6");
        params = MD5Utils.encryptParams(params);

        if (!checkSubmitInfo(params)) return;
        mSubscription = dataManager.getCarTypes(params).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<CarTypeModel>() {
                    @Override
                    public void onCompleted() {
//                        view.dismissDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e != null && mView != null) {
                            mView.brandSeriesFail(e.getMessage());
                        }
                    }

                    @Override
                    public void onNext(CarTypeModel successData) {
                        if(successData.getStatus()== Constant.SUCCESS) {
                            mView.brandSeriesSuccess(successData);
                        }else{
                            if(TextUtils.isEmpty(successData.getMsg())){
                                return;
                            }
                            mView.brandSeriesFail(successData.getMsg());
                        }
                    }
                });

    }

}
